package com.yxy.search;

import java.io.*;
import java.util.Date;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class IndexFiles
{

    private IndexFiles()
    {
    }

    public static void main(String args[])
    {
        String usage = "java org.apache.lucene.demo.IndexFiles [-index INDEX_PATH] [-docs DOCS_PATH] [-update]\n\nThis indexes the documents in DOCS_PATH, creating a Lucene indexin INDEX_PATH that can be searched with SearchFiles";
        String indexPath = "index";
        String docsPath = null;
        boolean create = true;
        for(int i = 0; i < args.length; i++)
        {
            if("-index".equals(args[i]))
            {
                indexPath = args[i + 1];
                i++;
                continue;
            }
            if("-docs".equals(args[i]))
            {
                docsPath = args[i + 1];
                i++;
                continue;
            }
            if("-update".equals(args[i]))
                create = false;
        }

        if(docsPath == null)
        {
            System.err.println((new StringBuilder()).append("Usage: ").append(usage).toString());
            System.exit(1);
        }
        File docDir = new File(docsPath);
        if(!docDir.exists() || !docDir.canRead())
        {
            System.out.println((new StringBuilder()).append("Document directory '").append(docDir.getAbsolutePath()).append("' does not exist or is not readable, please check the path").toString());
            System.exit(1);
        }
        Date start = new Date();
        try
        {
            System.out.println((new StringBuilder()).append("Indexing to directory '").append(indexPath).append("'...").toString());
            Directory dir = FSDirectory.open(new File(indexPath));
            Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);
            IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40, analyzer);
            if(create)
                iwc.setOpenMode(org.apache.lucene.index.IndexWriterConfig.OpenMode.CREATE);
            else
                iwc.setOpenMode(org.apache.lucene.index.IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
            IndexWriter writer = new IndexWriter(dir, iwc);
            indexDocs(writer, docDir);
            writer.close();
            Date end = new Date();
            System.out.println((new StringBuilder()).append(end.getTime() - start.getTime()).append(" total milliseconds").toString());
        }
        catch(IOException e)
        {
            System.out.println((new StringBuilder()).append(" caught a ").append(e.getClass()).append("\n with message: ").append(e.getMessage()).toString());
        }
    }

    static void indexDocs(IndexWriter writer, File file)
    {
        FileInputStream fis = null;
        if(!file.canRead())
        if(file.isDirectory())
        {
            String files[] = file.list();
            if(files != null)
            {
                for(int i = 0; i < files.length; i++)
                    indexDocs(writer, new File(file, files[i]));

            }
        }
         
            try {
				fis = new FileInputStream(file);
				Document doc = new Document();
				Field pathField = new StringField("path", file.getPath(), org.apache.lucene.document.Field.Store.YES);
				doc.add(pathField);
				doc.add(new LongField("modified", file.lastModified(), org.apache.lucene.document.Field.Store.NO));
				doc.add(new TextField("contents", new BufferedReader(new InputStreamReader(fis, "UTF-8"))));
				if(writer.getConfig().getOpenMode() == org.apache.lucene.index.IndexWriterConfig.OpenMode.CREATE)
				{
				    System.out.println((new StringBuilder()).append("adding ").append(file).toString());
				    writer.addDocument(doc);
				} else
				{
				    System.out.println((new StringBuilder()).append("updating ").append(file).toString());
				    writer.updateDocument(new Term("path", file.getPath()), doc);
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally{
				try {
					fis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
    }
}

